const express = require('express');
const cors = require('cors');
const path = require('path');
require('dotenv').config();

const neo4jService = require('./services/neo4jService');
const graphRoutes = require('./routes/graphRoutes');

const app = express();
const PORT = process.env.PORT || 3000;

// 中间件配置
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// 静态文件服务
app.use(express.static(path.join(__dirname, 'public')));

// API路由
app.use('/api/graph', graphRoutes);

// 设置相关路由
app.use('/api/settings', require('./routes/settingsRoutes'));

// 主页路由
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

// 健康检查
app.get('/health', async (req, res) => {
  try {
    const isConnected = await neo4jService.testConnection();
    res.json({ 
      status: 'ok', 
      neo4j: isConnected ? 'connected' : 'disconnected',
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    res.status(500).json({ 
      status: 'error', 
      message: error.message,
      timestamp: new Date().toISOString()
    });
  }
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('服务器错误:', err.stack);
  res.status(500).json({ 
    error: '服务器内部错误',
    message: process.env.NODE_ENV === 'development' ? err.message : '请稍后重试'
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log(`🚀 知识图谱服务器运行在 http://localhost:${PORT}`);
  console.log(`📊 Neo4j连接: ${process.env.NEO4J_URI}`);
  
  // 测试数据库连接
  neo4jService.testConnection()
    .then(connected => {
      if (connected) {
        console.log('✅ Neo4j数据库连接成功');
      } else {
        console.log('❌ Neo4j数据库连接失败');
      }
    })
    .catch(err => {
      console.error('❌ Neo4j连接错误:', err.message);
    });
});

// 优雅关闭
process.on('SIGINT', async () => {
  console.log('\n正在关闭服务器...');
  await neo4jService.close();
  process.exit(0);
});

module.exports = app;